package dw.fastfile.common.validation;

import dw.fastfile.common.annotations.Dict;
import dw.fastfile.common.enums.EnumFieldService;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @description: 校验字典
 * @author: wanghao
 * @create: 2024-01-31 14:18
 **/
@Slf4j
public class DictValidation implements ConstraintValidator<Dict, Object> {
    @Resource
    private EnumFieldService enumFieldService;

    private String type;
    private String message;

    @Override
    public void initialize(Dict constraintAnnotation) {
        this.type = constraintAnnotation.dictType();
        this.message = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        log.info("进入了校验：" + o);
        // 不用默认的错误消息
        constraintValidatorContext.disableDefaultConstraintViolation();

        try {
            Object name = enumFieldService.getName(this.type, o + "");
            if (name != null) {
                return true;
            }

            constraintValidatorContext.buildConstraintViolationWithTemplate(this.message).addConstraintViolation();
            return false;

        } catch (Exception e) {
            constraintValidatorContext.buildConstraintViolationWithTemplate("枚举不存在：" + this.type).addConstraintViolation();
            return false;
        }

    }
}
